package com.sllp.C71S3TsllpShop.web;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.http.converter.json.GsonFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sllp.C71S3TsllpShop.bean.ChatRecord;
import com.sllp.C71S3TsllpShop.dao.ChatRecordMapper;
import com.sllp.C71S3TsllpShop.util.RedisUtil;


//浏览器与服务器通讯时会发起 /websocket 请求 会自动来到这里进行链接
@ServerEndpoint(value = "/websocket/{id}")
@Component
public class ChatAction {
	
	

	// 存放线程安全的集合
	private static Hashtable<String, Session> sessionTable = new Hashtable<String, Session>();

	//此处是解决无法注入的关键
    private static ApplicationContext applicationContext;
    //要注入的service或者dao
    private RedisUtil redisUtil;
	private ChatRecordMapper crm;
    public static void setApplicationContext(ApplicationContext applicationContext) {
    	ChatAction.applicationContext = applicationContext;
    }
    
	/**
	 * 连接建立成功调用的方法 ，哪个session 对象就会被容器创建
	 * 
	 * @param session
	 */
	@OnOpen
	public void onOpen(@PathParam("id") String id, Session session) {
		sessionTable.put(id, session);
	}

	// 链接关闭调用的方法
	@OnClose
	public void onClose(@PathParam("id") String userId,Session session) {
		try {
			crm=applicationContext.getBean(ChatRecordMapper.class);
			redisUtil=applicationContext.getBean(RedisUtil.class);
			ObjectMapper mapper = new ObjectMapper();
			System.out.println(userId); 
			String jsonObj="";
			if(userId.indexOf("user") == 0) {
				// 用户关闭聊天连接 将redis中的聊天记录存放到mysql数据库中
				if(redisUtil.hasKey(userId)) {
					jsonObj = (String) redisUtil.get(userId);
				}
				List<ChatRecord> chatRecords = null;
				if(jsonObj != "") {
					chatRecords= mapper.readValue(jsonObj, new TypeReference<List<ChatRecord>>(){});
				}
				if(chatRecords != null) {
					int flag=0;
					for (ChatRecord chatRecord : chatRecords) {
						flag = crm.insertSelective(chatRecord);
					}
					if(flag>0) {
						redisUtil.del(userId);
					}
				}
			}
			sessionTable.remove(userId);
			session.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 收到客户端消息后调用的方法
	@OnMessage
	public void onMessage(@PathParam("id") String id, String message, Session session) {
		try {
			redisUtil=applicationContext.getBean(RedisUtil.class);
			System.out.println(message+"=="+id);
			String[] idAndMsg = message.split(":");
			Session destSession = sessionTable.get(idAndMsg[0]);
			
			int businessId = 0;
			int userId = 0;
			List<ChatRecord> chatRecords = new ArrayList<ChatRecord>();
			String jsonObj="";
			int c = id.indexOf("user");
			int who = 0 ;
			if(c==0) {// 发送消息的是用户
				who=1;
				userId=Integer.valueOf(id.substring(4));
				businessId=Integer.valueOf(idAndMsg[0].substring(8));
				System.out.println(redisUtil);
				if(redisUtil.hasKey(id)) {
					jsonObj = (String) redisUtil.get(id);
				}
			}else if(id.indexOf("business") == 0){// 发送消息的是商家
				who=2;
				businessId=Integer.valueOf(id.substring(8)); 
				userId=Integer.valueOf(idAndMsg[0].substring(4));
				if(redisUtil.hasKey(id)) {
					jsonObj = (String) redisUtil.get(idAndMsg[0]);
				}
			}
			ObjectMapper mapper = new ObjectMapper();
			if(jsonObj != "") {
				chatRecords= mapper.readValue(jsonObj, new TypeReference<List<ChatRecord>>(){});
			}
			
			// 如果没有此用户的聊天记录则将其进行记录
			if(chatRecords.size() == 0) {
				chatRecords = new ArrayList<ChatRecord>();
				ChatRecord chatRecord = new ChatRecord();
				chatRecord.setBusiness(businessId);
				chatRecord.setMessage(idAndMsg[1]);
				chatRecord.setSendTime(new Timestamp(System.currentTimeMillis()));
				chatRecord.setUser(userId);
				chatRecord.setWho(who);
				chatRecords.add(chatRecord);
			}else {
				ChatRecord chatRecord = new ChatRecord();
				chatRecord.setBusiness(businessId);
				chatRecord.setMessage(idAndMsg[1]);
				chatRecord.setSendTime(new Timestamp(System.currentTimeMillis()));
				chatRecord.setUser(userId);
				chatRecord.setWho(who);
				chatRecords.add(chatRecord);
			}
			String jsonString=mapper.writeValueAsString(chatRecords);
			redisUtil.set("user"+userId, jsonString);
			redisUtil.set("business"+businessId, jsonString);
			
		
			if (destSession != null) {
				destSession.getBasicRemote().sendText(idAndMsg[1]);
			}else {
				sessionTable.get(id).getBasicRemote().sendText("此用户不在线...");
				System.out.println("目标用户不在线..."+idAndMsg[0]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
